<?php

namespace common\components;

use Yii;
use common\models\rbac\Menu;
use common\helpers\MenuHelper;
use common\helpers\ArrayHelper;

/**
 * CModule is this application base class for module.
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class BaseModule extends \yii\base\Module {

    public $layout = '/module';

    /**
     * @var boolean 设置是否仅显示授权菜单
     */
    public $onlyViewAuthMenu = true;

    /**
     * @var boolean
     */
    public $assignment = true;

    /**
     * @var array
     * @see [[menus]]
     */
    private $_menus = [];

    /**
     * @var string
     */
    private $_assetsUrl;

    public function init() {
        parent::init();
        $this->loadLocalConfig();
    }

    /**
     * 加载模块下自定义配置
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param  integer $id
     * @return Menu the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function loadLocalConfig() {
        $config = $this->getBasePath() . DIRECTORY_SEPARATOR . 'config/main.php';
        if (file_exists($config)) {
            Yii::configure($this, require $config);
        }
    }

    /**
     * Finds the Custorm model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param  integer $id
     * @return Menu the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        $model = Menu::findOne($id);
        if ($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        return $model;
    }

    public function getAssetsUrl() {
        if ($this->_assetsUrl === null) {
            $this->_assetsUrl = Yii::$app->assetManager->getPublishedUrl('@webroot/themes');
        }
        return $this->_assetsUrl;
    }

    /**
     * Get available menu.
     * @return array
     */
    public function getMenus() {
        if (empty($this->_menus)) {
            $this->setMenus();
        }
        return $this->_menus;
    }

    /**
     * Set or add available menu.
     * @param array $menus
     */
    public function setMenus($menus = []) {
        $authMenus = [];
        $uniqueId = $this->getUniqueId();
        $moduleMenu = Menu::findOne([
            'route' => '/' . $uniqueId . '/*'
        ]);
        if ($moduleMenu) {
            $authMenus = MenuHelper::getAssignedModuleMenu(Yii::$app->user->id, $moduleMenu->topParentId);
        }
        $this->_menus = ArrayHelper::merge($authMenus, $menus);
    }

}
